package controller;

import util.CommonUtil;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/captche")
public class CaptcheController extends HttpServlet {
    private final int WIDTH = 170;
    private final int HEIGHT = 50;
    private HttpSession session = null;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedImage img = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
        Graphics g = img .getGraphics();//画笔
        g.setColor(Color.black);
        g.fillRect(0,0,WIDTH,HEIGHT);//画笔填充矩形

        g.setColor(Color.yellow); //字体颜色
        String code = CommonUtil.randStr(4);
        session = req.getSession();
        session.setAttribute("code", code.replace(" ", "")); //将验证码存储在session中
        g.setFont(new Font("Times New Roman",Font.BOLD,50)); //设置字体大小型号
        g.drawString(code,WIDTH/4,12+HEIGHT/2);

        g.setColor(Color.green);
        for(int i = 0;i<50;i++){  //生成随机位置点
            Random ran = new Random();
            int x = ran.nextInt(WIDTH);
            int y = ran.nextInt(WIDTH);
            g.drawOval(x,y,1,1);
        }

        g.setColor(Color.ORANGE);
        for(int i = 0;i<7;i++){   //生成随机线条
            Random ran = new Random();
            int x1 = ran.nextInt(WIDTH);
            int x2 = ran.nextInt(WIDTH);
            int y1 = ran.nextInt(HEIGHT);
            int y2 = ran.nextInt(HEIGHT);
            g.drawLine(x1,y1,x2,y2);
        }

        g.dispose();

        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(img,"jpg",out);
        try{
            out.flush();
        }finally {
            out.close();
        }

    }

}
